package sohsite.reserva.servlets;

import java.io.IOException;
import java.sql.Timestamp;
import java.util.Collection;
import java.util.HashSet;
import java.util.StringTokenizer;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import sohsite.excecao.EntradaInexistenteException;
import sohsite.fachada.SistemaSohSite;
import sohsite.pelada.pelada.Pelada;
import sohsite.reserva.Reserva;
import sohsite.usuario.Usuario;

public class ServletInserirReserva extends HttpServlet {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	public void doPost (HttpServletRequest req,
			HttpServletResponse res)
	throws ServletException, IOException
	{	
		
		System.out.println("ENTROOOOOOOOOOOOOOOOOOOOU");
		SistemaSohSite sohSite = SistemaSohSite.getInstancia();

		String reserva = req.getParameter("horarioReserva");
		int idUsuario = Integer.parseInt(req.getParameter("idUsuario"));
		String url = req.getParameter("url");
		String pel = req.getParameter("peladaReserva");
		System.out.println("OLHA AEEEEEEEEEEEEEEEEEE" + pel);
		Pelada pelada = null;
		
		if(pel != null && !pel.trim().equals("")){
			try{
				pelada = sohSite.getControladorPelada().consultarPelada(Integer.parseInt(pel));
			}catch(EntradaInexistenteException e){
				
			}
		}

		StringTokenizer token = new StringTokenizer(reserva,";");
		int hora = Integer.parseInt(token.nextToken());
		int dia = Integer.parseInt(token.nextToken());
		int mes = Integer.parseInt(token.nextToken());
		int ano = Integer.parseInt(token.nextToken());
		
		Usuario u = null;
		
		try {
			u = sohSite.getControladorUsuario().consultarUsuario(idUsuario);
		} catch (EntradaInexistenteException e) {
			System.out.println("PAUUUUUU");
		}
		
		Timestamp t = new Timestamp(ano,mes,dia,hora,0,0,0);
		
		Reserva reser = new Reserva();
		reser.setStatus("confirmada");
		reser.setUsuario(u);
		reser.setData(t);
		if(pelada != null){
			reser.setPelada(pelada);
		}
		
		
		sohSite.getControladorReserva().inserirReserva(reser);

		res.sendRedirect(url);
	}

}